package cn.bearspark.api.service.func.impl;

import cn.bearspark.api.service.func.MeritService;
import cn.bearspark.article.rpc.ArticleRpc;
import cn.bearspark.common.constant.GlobalConstant;
import cn.bearspark.common.enumeration.ModuleEnum;
import cn.bearspark.currency.rpc.CurrencyRpc;
import cn.bearspark.framework.web.starter.context.BSRequestContext;
import cn.bearspark.framework.web.starter.vo.ResponseVO;
import cn.bearspark.merit.rpc.AccMeritRpc;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

/**
 * @author f
 */
@Service
public class MeritServiceImpl implements MeritService {

    @DubboReference(check = GlobalConstant.DUBBO_CHECK)
    private AccMeritRpc accMeritRpc;
    @DubboReference(check = GlobalConstant.DUBBO_CHECK)
    private CurrencyRpc currencyRpc;
    @DubboReference(check = GlobalConstant.DUBBO_CHECK)
    private ArticleRpc articleRpc;

    @Override
    public ResponseVO<Object> meritArticle(Long articleId) {
        long userId = BSRequestContext.getUserId();

        // 判断该用户是否向该专栏积过功德，如果积过，则直接返回
        if (accMeritRpc.isMerited(userId, ModuleEnum.ARTICLE.getCode(), articleId)) {
            return ResponseVO.badRequest("已经积过功德了");
        }

        // 扣减用户的功德数，如果扣减失败，则直接返回
        if (!currencyRpc.deductMerit(userId)) {
            return ResponseVO.badRequest("没有足够的功德");
        }

        // 记录该用户向该专栏积功德
        accMeritRpc.meritArticle(userId, ModuleEnum.ARTICLE.getCode(), articleId);

        // 专栏的功德数加一
        articleRpc.incrMeritNum(articleId);

        return ResponseVO.success();
    }
}
